package org.gg.boom.modules.sys.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.gg.boom.common.controller.BaseController;
import org.gg.boom.common.model.Response;
import org.gg.boom.common.utils.StringUtils;
import org.gg.boom.common.utils.poi.ExcelUtil;
import org.gg.boom.kernel.annotation.Log;
import org.gg.boom.kernel.enums.BusinessType;
import org.gg.boom.kernel.web.service.SysPermissionService;
import org.gg.boom.kernel.web.service.TokenService;
import org.gg.boom.modules.sys.model.LoginUser;
import org.gg.boom.modules.sys.model.entity.SysUserRole;
import org.gg.boom.modules.sys.model.param.SysDeptParam;
import org.gg.boom.modules.sys.model.param.SysRoleParam;
import org.gg.boom.modules.sys.model.param.SysUserParam;
import org.gg.boom.modules.sys.model.vo.SysRoleResult;
import org.gg.boom.modules.sys.model.vo.SysUserResult;
import org.gg.boom.modules.sys.service.SysDeptService;
import org.gg.boom.modules.sys.service.SysRoleService;
import org.gg.boom.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 角色信息
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysDeptService deptService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public Response list(SysRoleParam param) {
        Page<SysRoleResult> page = roleService.selectRoleList(param);
        return getDataTable(page);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRoleParam param) {
        Page<SysRoleResult> page = roleService.selectRoleList(param);
        ExcelUtil<SysRoleResult> util = new ExcelUtil<>(SysRoleResult.class);
        util.exportExcel(response, page.getRecords(), "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public Response getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Response add(@Validated @RequestBody SysRoleParam param) {
        return toResponse(roleService.insertRole(param));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response edit(@Validated @RequestBody SysRoleParam param) {
        roleService.checkRoleAllowed(param.getRoleId());
        roleService.checkRoleDataScope(param.getRoleId());
        if (roleService.updateRole(param) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改角色'" + param.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public Response dataScope(@RequestBody SysRoleParam param) {
        roleService.checkRoleAllowed(param.getRoleId());
        roleService.checkRoleDataScope(param.getRoleId());
        return toResponse(roleService.authDataScope(param));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public Response changeStatus(@RequestBody SysRoleParam param) {
        roleService.checkRoleAllowed(param.getRoleId());
        roleService.checkRoleDataScope(param.getRoleId());
        return toResponse(roleService.updateRoleStatus(param));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public Response remove(@PathVariable Long[] roleIds) {
        return toResponse(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public Response optionselect() {
        return success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    public Response allocatedList(SysUserParam param) {
        Page<SysUserResult> page = userService.selectAllocatedList(param);
        return getDataTable(page);
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    public Response unallocatedList(SysUserParam param) {
        Page<SysUserResult> list = userService.selectUnallocatedList(param);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public Response cancelAuthUser(@RequestBody SysUserRole userRole) {
        return toResponse(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public Response cancelAuthUserAll(Long roleId, Long[] userIds) {
        return toResponse(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public Response selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return toResponse(roleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    public Response deptTree(@PathVariable("roleId") Long roleId) {
        JSONObject result = new JSONObject();
        result.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        result.put("depts", deptService.selectDeptTreeList(new SysDeptParam()));
        return success(result);
    }
}
